var process = require('process');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var morganLogger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var util = require('./util')
var config = require('./config')
var db = require('./db_helper')
var api = require('./routes/api');
var pubSelf = require('./routes/pub-self');
var pubBook = require('./routes/pub-book');

var app = express();
var logger = util.logger;


process.on('uncaughtException', (err) => {
  logger.error('未捕获的异常:', err);
})

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(morganLogger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', (req, res, next) => {
  logger.debug('url: ' + req.url)
  if (req.url === '/' || req.url.startsWith('/index.html')){
    let token = req.cookies.token;
    logger.debug('check token: %s', token)
    if (db.checkToken(token)) {
      logger.debug('token check success')
      next()
    }else{
      logger.debug('token check fail')
      res.redirect('/login.html');
    }
  }else{
    next()
  }
})

/**
 * gitbook拦截器
 */
app.use('/docs/', (req, res, next) => {
  if (req.url.endsWith('favicon.ico')) {
    res.redirect('/images/favicon.ico');
  }else{
    let token = req.cookies.token;
    logger.debug('user token : %s', token);
    if (token) {
      let auth = db.getAuth(token);
      logger.debug('user auth : ', auth)
      if (auth) {
        let begin = req.url.lastIndexOf('/docs')
        let paths = decodeURIComponent(req.url.substring(begin)).split('/');
        if (db.defaultAuth.indexOf(paths[1]) !== -1){
          next();
        }else{
          logger.debug(`url paths length ${paths.length} : `, paths);
          if (paths.length > 2){
            let project = paths[2];
            logger.debug('look at project: %s', project);
            if (auth.indexOf(project) === -1){
              logger.debug('have not auth: %s', project)
              res.redirect(config.book_error_path);   //书籍异常页面
            }else{
              logger.debug('auth done ...') 
              next();
            }
          }else{
            next();
          } 
        }
      }else{
        res.redirect('/login.html');
      }
    }else{
      res.redirect('/login.html');
    }
  }
  // next()
});

app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', api);
app.use('/pub-self', pubSelf);
app.use('/pub-book', pubBook);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;
